package com.floretexaminaction.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.floretexaminaction.dao.ClassManageDao;
import com.floretexaminaction.dao.TeacherDao;
import com.floretexaminaction.model.ClassManageEntity;
import com.floretexaminaction.model.StudentEntity;
import com.floretexaminaction.model.TeacherEntity;
import com.floretexaminaction.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Random;

@RestController
@Slf4j
public class AdminController {

    /**
     * 打印日志
     */
    Log log = LogFactory.getLog("三岁小仙仙");

    /**
     * 教师数据层操作
     */
    @Autowired
    private TeacherDao teacherDao;

    /**
     * jdbcTemplate
     */
    @Autowired
    private UserService userService;

    /**
     * 班级目录
     */
    @Autowired
    private ClassManageDao classManageDao;

    /**
     * 下载教师excel模板
     * @param response
     * @type 下载模板类型 student/teacher
     * @throws IOException
     */
    @GetMapping("/downloadTemplate")
    private String downloadTemplate(HttpServletResponse response, String type) throws IOException {
        Resource resource = null;
        if(type.equals("student")){
             resource = new ClassPathResource("static/downloadTemplate/studentTemplate.xlsx");
        }else if (type.equals("teacher")){
             resource = new ClassPathResource("static/downloadTemplate/teacherTemplate.xlsx");
        }else{
            return "文件不存在";
        }
        File file = resource.getFile();
        String filename = resource.getFilename();
        if(file.exists()){
            response.setContentType("application/force-download");
            response.addHeader("content-disposition","attachment;filename="+ URLEncoder.encode(filename, "utf-8"));

            byte[] buffer = new byte[2048];
            FileInputStream fis = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fis);`
            int i = bis.read(buffer);
            OutputStream os = response.getOutputStream();
            while (i != -1){
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            if (bis!=null){bis.close();};
            if (fis!=null){fis.close();};
            return "";
        }else{
            PrintWriter pw = response.getWriter();
            pw.print("文件不存在！");
        }
        return "文件不存在";
    }


    /**
     * 添加教师信息
     * @param tableData 数组对象
     * @return
     */
    @PostMapping("/importTeachers")
    private String importTeachers(String tableData){
        List<TeacherEntity> teacherEntityList = JSONArray.parseArray(tableData, TeacherEntity.class);
        String result = userService.saveBatch(teacherEntityList, "teacher");
        return result;
    }

    /**
     * 更新教师信息
     * @param updateArr 数组对象
     * @return 更新数量
     */
    @PostMapping("/updateTearcher")
    private int updateTearcher(String updateArr){
        List<TeacherEntity> list = JSONArray.parseArray(updateArr, TeacherEntity.class);
        userService.batchUpdate(list);
        return list.size();
    }

    /**
     * 删除教师信息
     * @param deleteArr 数组对象
     * @return 删除数量
     */
    @PostMapping("/deleteTeacher")
    private int deleteTeacher(String deleteArr){
        JSONArray jsonArray = JSONArray.parseArray(deleteArr);
        for(int i = 0 ; i < jsonArray.size() ; i++){
            teacherDao.deleteById(jsonArray.getString(i));
        }
        return jsonArray.size();
    }

    /**
     * 自动获取所有教师信息
     * @return 数组对象
     */
    @GetMapping("/autoGetTeachers")
    private String autoGetTeachers(){
        Iterable<TeacherEntity> teacherDaoAll = teacherDao.findAll();
        Object o = JSON.toJSON(teacherDaoAll);
        return o.toString();
    }

    /**
     * 创建班级
     * @param classArr 数组对象
     * @return 创建成功true/false
     */
    @PostMapping("/createClass")
    private boolean createClass(String classArr){
        JSONObject jsonObject = JSONObject.parseObject(classArr);
        ClassManageEntity ce = new ClassManageEntity();
        ce.setClassName(jsonObject.getString("className"));
        ce.setClassNumber(jsonObject.getString("classNumber"));
        boolean present = classManageDao.findById(ce.getClassNumber()).isPresent();
        if(present){
            return false;
        }
        ClassManageEntity save = classManageDao.save(ce);
        userService.createClass(ce.getClassNumber(), ce.getClassName());
        return true;
    }

    /**
     * 删除班级
     * @param classNumber 班级编号
     * @return
     */
    @PostMapping("/deleteClass")
    private String deleteClass(String classNumber){
        String res = userService.deleteClass(classNumber);
        classManageDao.deleteById(classNumber);
        return res;
    }

    /**
     * 获取班级列表
     * @return json班级列表
     */
    @GetMapping("/getClassList")
    private String getClassList(){
        Iterable<ClassManageEntity> all = deleteClass.findAll();
        String jsonString = JSON.toJSONString(all);
        return jsonString;
    }

    /**
     * 添加学生、修改学生信息
     * @param classNumber 班级号
     * @param updateArr 数组对象
     * @return 添加修改数
     */
    @PostMapping("/importStudent")
    private String importStudent(String classNumber, String updateArr){
        List<StudentEntity> studentEntities = JSONArray.parseArray(updateArr, StudentEntity.class);
        String saveBatch = userService.saveBatch(studentEntities, classNumber);
        if(saveBatch.equals("true")){
            return String.valueOf(studentEntities.size());
        }
        return saveBatch;
    }

    /**
     * 根据班级号和学号删除指定的学生信息
     * @param studentNumber 学号-班级号
     * @return ""
     */
    @PostMapping("/deleteStudent")
    private int deleteStudent(String studentNumber){
        JSONArray jsonArray = JSONArray.parseArray(studentNumber);
        for (int i = 0 ; i < jsonArray.size() ; i++){
            log.info(jsonArray.get(i));
            String className = jsonArray.get(i).toString().substring(0, 7);
            userService.byClassNumberOrStudentNumberDelete(className, jsonArray.get(i).toString());
        }
        return jsonArray.size();
    }

    /**
     * 根据班级号获取本班学生信息
     * @param classNumber 班级号
     * @return 学生列表
     */
    @PostMapping("/autoGetStudents")
    private String autoGetStudents(String classNumber){
        String s = userService.queryClassStuFindNumber(classNumber);
        List<StudentEntity> studentEntities = JSONArray.parseArray(s, StudentEntity.class);
        return JSON.toJSONString(studentEntities);
    }

}
